//
//  ViewController.m
//  ibeaconDemo
//
//  Created by 江苏宏创 on 14-7-8.
//  Copyright (c) 2014年 qkong. All rights reserved.
//

#import "HCViewController.h"
#import "HCFileOperation.h"
#import "HCSendHttpOperation.h"
#import "HCMacroDefinition.h"
#import "HCFoodDetailView.h"
#import "HCHWLabelTextSize.h"
#import "HCHelpViewDsiplay.h"
#import "NSString+FontAwesome.h"

static int height1 = 80;
static int height2 = 60;
//static int height3 = 100;

@interface HCViewController ()
{
    NSDictionary       *ibeaconUUIDInfoDic; //默认ibeacon配置信息
    NSMutableArray     *displayArr;         //历史请求的数据纪录
    
    UIView             *tipView;

    IBOutlet UITableView        *historyTable; //展示历史纪录表
    IBOutlet UISegmentedControl *historySeg;
    
    int  count;
}

@property (nonatomic,strong) UIImageView *ibeaconView;
@property NSMutableDictionary            *beacons;
@property CLLocationManager              *locationManager;
@property NSMutableDictionary            *rangedRegions;

@end

@implementation HCViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
    
    for (CLBeaconRegion *region in self.rangedRegions)
    {
        [self.locationManager startRangingBeaconsInRegion:region];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    for (CLBeaconRegion *region in self.rangedRegions)
    {
        [self.locationManager stopRangingBeaconsInRegion:region];
    }
}

- (void)navigationShowRight
{
    HCHelpViewDsiplay *instance = [[HCHelpViewDsiplay alloc] init];
    [self.navigationController pushViewController:instance animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"HCtitle", @"");
    
    
    UIButton* button= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [button.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:26]];
    [button setTitle:[NSString fontAwesomeIconStringForIconIdentifier:@"fa-info-circle"] forState:UIControlStateNormal];
    
    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame     = CGRectMake(0, 0, 30, 30);
//    [button setBackgroundImage:[UIImage imageNamed:@"HCHelplogo"] forState:UIControlStateNormal];
//    [button setBackgroundImage:[UIImage imageNamed:@"HCHelplogo"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(navigationShowRight) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItemRight=[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem=barItemRight;
    
    //蓝牙
    self.beacons = [[NSMutableDictionary alloc] init];
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.activityType = CLActivityTypeFitness;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.rangedRegions = [[NSMutableDictionary alloc] init];
    
    //UIsegmentControl
    historySeg = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    historySeg.tintColor = HEX2UIColor(0x8aa600);
    
    [historySeg insertSegmentWithTitle:NSLocalizedString(@"HCSeg0", @"餐饮") atIndex:0 animated:YES];
    [historySeg insertSegmentWithTitle:NSLocalizedString(@"HCSeg1", @"服务") atIndex:1 animated:YES];
    
    NSDictionary* titleAttr = [NSDictionary dictionaryWithObjectsAndKeys:HEX2UIColor(0xffffff),UITextAttributeTextColor, nil];
    [[UISegmentedControl appearance] setTitleTextAttributes:titleAttr
                                                   forState:UIControlStateSelected];
    
    historySeg.selectedSegmentIndex = 0;
    [historySeg addTarget:self action:@selector(selectSegment) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = historySeg;
    
    //UITableView
    int height                  = (MODEL?568:480)-64;
    historyTable                = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, height)
                                                               style:UITableViewStylePlain];
    historyTable.delegate       = self;
    historyTable.dataSource     = self;
    historyTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view                  addSubview:historyTable];
    
    //创建uuid与时间对应列表
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString      *timeForUUIDpath  = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ibeacon.plist"];
    NSArray       *uuidList    = [[[NSDictionary alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"UUIDTypeList" ofType:@"plist"]] allKeys];
    NSMutableDictionary *timeForUUID = [[NSMutableDictionary alloc]init];
    for (NSString *uuid in uuidList)
        [timeForUUID setObject:@0 forKey:uuid];
    if (![fileManager fileExistsAtPath:timeForUUIDpath])
    {
        [fileManager createFileAtPath:timeForUUIDpath contents:nil attributes:nil];
        [timeForUUID writeToFile:timeForUUIDpath atomically:YES];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(tip:)
                                                 name:@"TIP"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshTableView:)
                                                 name:@"refreshTableView"
                                               object:nil];

    
    NSString *UUIDNamePath = [[NSBundle mainBundle] pathForResource:@"UUIDNameList" ofType:@"plist"];
    ibeaconUUIDInfoDic     = [[NSDictionary alloc] initWithContentsOfFile:UUIDNamePath];
    
    for (NSString *tempStr in [ibeaconUUIDInfoDic allKeys])
    {
        NSUUID *uuid           = [[NSUUID alloc] initWithUUIDString:tempStr];
        CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:tempStr];
        self.rangedRegions[region] = [NSArray array];
    }

    if(displayArr)
        displayArr = nil;
    //初始化展示数据
    displayArr = [[NSMutableArray alloc] initWithArray:[[HCFileOperation shareFileOperation] getSearchHistory:historySeg.selectedSegmentIndex]];
}

- (void)refreshTableView:(NSNotification *)noti
{
    id type = [[noti object] objectForKey:@"type"];
    historySeg.selectedSegmentIndex = [type intValue];
    [self selectSegment];
}

#pragma mark - Location manager delegate
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
    count++;
    if(count%100 == 0)
        NSLog(@"--->%d",count);
    if(count%1000==0)
    {
        NSLog(@"+++>%d",count);
        [self sendLocalNotification:@"12345678-2222-2222-8F0C-720EAF059935"];
        [self sendLocalNotification:@"74278BDA-B644-4520-8F0C-720EAF059935"];
    }
    
    if (beacons.count)
    {
        for (int i = 0; i< beacons.count; i++)
        {
            CLBeacon *beacon =[beacons objectAtIndex:i];
            
            NSString * info_1 = [NSString stringWithFormat:@"UUIDString:%@",beacon.proximityUUID.UUIDString];
            NSString * info_2 = [NSString stringWithFormat:@"major:%@",beacon.major];
            NSString * info_3 = [NSString stringWithFormat:@"minor:%@",beacon.minor];
            NSString * info_4 = [NSString stringWithFormat:@"accuracy:%0.4f米",beacon.accuracy];
            NSString * debugInfo = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n",info_1,info_2,info_3,info_4];
            NSLog(@"debugInfo-->%d-->%@",i,debugInfo);
            
            if(beacon.accuracy>0)
            {
                if(beacon.accuracy <= DISTANCE)
                {
                    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ibeacon.plist"];
                    
                    NSMutableDictionary *compareTime = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
                    if (![[compareTime objectForKey:beacon.proximityUUID.UUIDString] isKindOfClass:[NSDate class]]) {
                        //第一次进入应用
                        [compareTime setObject:[NSDate date] forKey:beacon.proximityUUID.UUIDString];
                        [compareTime writeToFile:path atomically:YES];
                        [self sendLocalNotification:beacon.proximityUUID.UUIDString];
                        NSLog(@"uuid--->%@",beacon.proximityUUID.UUIDString);
                    }else{
                        NSDate *backup = [compareTime objectForKey:beacon.proximityUUID.UUIDString];
                        NSDate *now = [NSDate date];
                        NSTimeInterval cha = [now timeIntervalSinceDate:backup];
                        NSLog(@"cha--->%f",cha);
                        if (cha > TIME_DEAL) {
                            [self sendLocalNotification:beacon.proximityUUID.UUIDString];
                            [compareTime setObject:[NSDate date] forKey:beacon.proximityUUID.UUIDString];
                            [compareTime writeToFile:path atomically:YES];
                        }
                    }
                }
            }
        }
    }
}

- (void)sendLocalNotification:(NSString *)uuid
{
        UILocalNotification *notice = [[UILocalNotification alloc] init];
        NSString *param = [NSString stringWithFormat:@"%@",[ibeaconUUIDInfoDic objectForKey:uuid]];
        notice.alertBody = param;
        notice.userInfo = @{@"uuid":uuid};
        
        notice.soundName = UILocalNotificationDefaultSoundName;
        [[UIApplication sharedApplication] scheduleLocalNotification:notice];
    
        HCSendHttpOperation *sendHttpOperation = [HCSendHttpOperation shareSendHttpRequest];
        [sendHttpOperation getDataWithUUID:uuid];
        NSLog(@"http请求了");
}

- (void)selectSegment
{
    if(displayArr)
        displayArr = nil;
    
    displayArr = [[NSMutableArray alloc] initWithArray:[[HCFileOperation shareFileOperation] getSearchHistory:historySeg.selectedSegmentIndex]];
    
    if(historyTable)
        [historyTable reloadData];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (historySeg.selectedSegmentIndex)
    {
        case 0:
            return height1;
            break;
        case 1:
        {
            NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
            
            
            CGSize size = [HCHWLabelTextSize getSuitSizeWithString:displayArr[indexPath.row][keyStr][@"serviceCentreInfo"][NSLocalizedString(@"HCserviceCentreInfo_content", @"")]
                                                        fontSize:13.0f
                                                            bold:NO
                                                         sizeOfX:240];
            
            return height2+size.height;
        }
            break;
//        case 2:
//        {
//            //文化活动
//            NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
//            CGSize size = [HCHWLabelTextSize getSuitSizeWithString:displayArr[indexPath.row][keyStr][NSLocalizedString(@"HCactivity_content", @"")]
//                                                        fontSize:13.0f
//                                                            bold:NO
//                                                         sizeOfX:300];
//            return height3+size.height;
//        }
//            break;
        default:
            return 80;
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return displayArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundColor = [UIColor clearColor];
    }
    
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews)
    {
        [subview removeFromSuperview];
    }
    
    UIImageView *line = [[UIImageView alloc] init];
    line.backgroundColor = TABLE_LINE;
    [cell.contentView addSubview:line];
    
    switch (historySeg.selectedSegmentIndex)
    {
        case 0:
        {
            //食堂
            line.frame = CGRectMake(0, height1-1, 320, 1);
            
            NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
            NSString *imgName = [NSString stringWithFormat:@"HC%@.png",displayArr[indexPath.row][keyStr][0][@"canteen"]];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(6, 10, 60, 60)];
            image.image = [UIImage imageNamed:imgName];
            [cell.contentView addSubview:image];
            
            UILabel *canteen = [[UILabel alloc] initWithFrame:CGRectMake(20, (height1-50)/2-2, 40, 50)];
            canteen.text = displayArr[indexPath.row][keyStr][0][NSLocalizedString(@"canteen", @"")];
            canteen.font = HEIGHT_FONT(15.0f);
            canteen.numberOfLines = 2;
            canteen.textColor = [UIColor whiteColor];
            canteen.transform = CGAffineTransformMakeRotation(-M_PI/7);
            [cell.contentView addSubview:canteen];
        
            UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 200, 20)];
            name.text = displayArr[indexPath.row][keyStr][0][@"foods"][0][NSLocalizedString(@"HCfoods_name", @"")];
            name.font = HEIGHT_FONT(17.0f);
            [cell.contentView addSubview:name];
            
            UILabel *description = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 210, 30)];
            description.numberOfLines = 2;
            description.font = NORMAL_FONT(12.0f);
            description.textColor = [UIColor grayColor];
            description.text = displayArr[indexPath.row][keyStr][0][@"foods"][0][NSLocalizedString(@"HCfoods_description", @"")];
            [cell.contentView addSubview:description];
            
            
            UILabel *pushTime = [[UILabel alloc] initWithFrame:CGRectMake(140, height1-15, 150, 15)];
            pushTime.textAlignment =NSTextAlignmentRight;
            pushTime.text = keyStr;
            pushTime.font = NORMAL_FONT(12.0f);
            pushTime.textColor = [UIColor grayColor];
            [cell.contentView addSubview:pushTime];
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
        case 1:
        {
            //服务中心
            UIImageView *imageLine2 = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, 1, height2)];
            imageLine2.backgroundColor = TABLE_LINE;
            [cell.contentView addSubview:imageLine2];
            
            UIImageView *imagelogo = [[UIImageView alloc] initWithFrame:CGRectMake(5, (height2-30)/2, 30, 30)];
            imagelogo.image = [UIImage imageNamed:@"HCcenter.png"];
            [cell.contentView addSubview:imagelogo];
            
            NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
            
            UILabel *typeName = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 240, 20)];
            typeName.font = HEIGHT_FONT(17.0f);
            typeName.text = displayArr[indexPath.row][keyStr][@"serviceCentreInfo"][NSLocalizedString(@"HCserviceCentreInfo_typeName", @"")];
            [cell.contentView addSubview:typeName];
            
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(50, 30, 240, 20)];
            title.font = NORMAL_FONT(13.0f);
            title.textColor = [UIColor grayColor];
            title.text = displayArr[indexPath.row][keyStr][@"serviceCentreInfo"][NSLocalizedString(@"HCserviceCentreInfo_title", @"")];
            [cell.contentView addSubview:title];
            
            UILabel *content = [[UILabel alloc] init];
            content.text = displayArr[indexPath.row][keyStr][@"serviceCentreInfo"][NSLocalizedString(@"HCserviceCentreInfo_content", @"")];
            CGSize size           = [HCHWLabelTextSize getSuitSizeWithString:content.text
                                                                    fontSize:13.0f
                                                                        bold:NO
                                                                     sizeOfX:240];
            content.frame         = CGRectMake(50, 45, 240, size.height+10);
            content.font          = NORMAL_FONT(13.0f);
            content.numberOfLines = 0;
            [cell.contentView     addSubview:content];
            
            UILabel *pushTime     = [[UILabel alloc] initWithFrame:CGRectMake(140, height2+size.height-15, 150, 15)];
            pushTime.textAlignment=NSTextAlignmentRight;
            pushTime.text         = keyStr;
            pushTime.font         = NORMAL_FONT(12.0f);
            pushTime.textColor    = [UIColor grayColor];
            [cell.contentView     addSubview:pushTime];
            
            line.frame            = CGRectMake(0, height2-1+size.height, 320, 1);
            imageLine2.frame      = CGRectMake(20, 0, 1, height2+size.height);
            imagelogo.frame       = CGRectMake(5, (height2+size.height-30)/2, 30, 30);
            
            cell.accessoryType    = UITableViewCellAccessoryNone;
        }
            break;
//        case 2:
//        {
//            //文化活动
//            UIImageView *imageLine2 = [[UIImageView alloc] init];
//            imageLine2.backgroundColor = TABLE_LINE;
//            [cell.contentView addSubview:imageLine2];
//            
//            UIImageView *imagelogo = [[UIImageView alloc] initWithFrame:CGRectMake(5, 15, 30, 30)];
//            imagelogo.image = [UIImage imageNamed:@"HCtimelogo.png"];
//            [cell.contentView addSubview:imagelogo];
//            
//            NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
//            
//            UIImageView *timeBackImg = [[UIImageView alloc] initWithFrame:CGRectMake(40, 16, 156, 28)];
//            timeBackImg.image = [UIImage imageNamed:@"HCtimeBack.png"];
//            [cell.contentView addSubview:timeBackImg];
//            
//            NSString *timeStr = [NSString stringWithFormat:@"%@ %@",displayArr[indexPath.row][keyStr][@"date"],displayArr[indexPath.row][keyStr][@"time"]];
//            UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(50, 18, 200, 24)];
//            time.text = timeStr;
//            time.textColor = [UIColor whiteColor];
//            time.font = NORMAL_FONT(13.0f);
//            [cell.contentView addSubview:time];
//            
//
//            UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(40, 50, 160, 20)];
//            name.text = displayArr[indexPath.row][keyStr][NSLocalizedString(@"HCactivity_name", @"")];
//            name.font = HEIGHT_FONT(17.0f);
//            [cell.contentView addSubview:name];
//            
//            UILabel *address = [[UILabel alloc] initWithFrame:CGRectMake(200, 50, 115, 20)];
//            address.text = displayArr[indexPath.row][keyStr][NSLocalizedString(@"HCactivity_address", @"")];
//            address.font = HEIGHT_FONT(13.0f);
//            address.textAlignment = NSTextAlignmentRight;
//            [cell.contentView addSubview:address];
//            
//            UILabel *content = [[UILabel alloc] init];
//            content.text = displayArr[indexPath.row][keyStr][NSLocalizedString(@"HCactivity_content", @"")];
//            CGSize size = [HCHWLabelTextSize getSuitSizeWithString:content.text fontSize:13.0f bold:NO sizeOfX:300];
//            content.frame = CGRectMake(40, 75, 275, size.height+10);
//            content.font = NORMAL_FONT(13.0f);
//            content.numberOfLines = 0;
//            [cell.contentView addSubview:content];
//            
//            
//            UILabel *pushTime = [[UILabel alloc] initWithFrame:CGRectMake(160, height3-1+size.height-15, 150, 15)];
//            pushTime.textAlignment =NSTextAlignmentRight;
//            pushTime.text = keyStr;
//            pushTime.font = NORMAL_FONT(12.0f);
//            pushTime.textColor = [UIColor grayColor];
//            [cell.contentView addSubview:pushTime];
//            
//            line.frame = CGRectMake(0, height3-1+size.height, 320, 1);
//            imageLine2.frame = CGRectMake(20, 0, 1, height3+size.height);
//            
//            cell.accessoryType = UITableViewCellAccessoryNone;
//        }
//            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(historySeg.selectedSegmentIndex == 0)
    {
        HCFoodDetailView *instance = [[HCFoodDetailView alloc] init];
        NSString *keyStr = [displayArr[indexPath.row] allKeys][0];
        instance.foodDisplayArr = displayArr[indexPath.row][keyStr];
        instance.pushTimeStr = keyStr;
        [self.navigationController pushViewController:instance animated:YES];
    }
}


//提醒方法
- (void)tip:(NSNotification *)noti
{
    id a = [noti object];
    NSString *msg = [a objectForKey:@"msg"];
    
    if(tipView)
        [tipView removeFromSuperview];
    
    int line = msg.length>20?2:1;
    
    tipView = [[UIView alloc] initWithFrame:CGRectMake(30, [[UIScreen mainScreen] bounds].size.height - 100, 260, 30+26*(line-1))];
    tipView.backgroundColor = [UIColor clearColor];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 260, 30+26*(line-1))];
    image.backgroundColor = [UIColor blackColor];
    image.alpha = 0.7;
    [tipView addSubview:image];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 7, 260, 19*line)];
    label.text = msg;
    label.numberOfLines = line;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0f];
    label.textColor = [UIColor whiteColor];
    [tipView addSubview:label];
    
    [self.view addSubview:tipView];
    
    [self performSelector:@selector(cancelAll) withObject:nil afterDelay:2];
}

- (void)cancelAll
{
    if(tipView)
        [tipView removeFromSuperview];
}


@end

